package cn.green.core.executor;

import cn.green.core.components.database.DBRouter;
import cn.green.core.components.database.entity.Database;
import cn.green.core.components.ddao.QDcl;
import cn.green.core.components.entity.DatabaseSql;
import cn.green.core.model.QField;
import cn.green.core.model.QTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author wang.yishu
 * @version 1.0
 * @className DclExecutor
 * @description 数据库控制语言
 * @date 2024/11/22 16:16
 */
public class DclExecutor {

    public DclExecutor(QDcl dcl, DBRouter dbRouter) {
        this.dbRouter = dbRouter;
        this.dcl = dcl;
    }

    private final QDcl dcl;
    private final DBRouter dbRouter;

    /**
     * 表是否存在
     * @param table
     * @return
     */
    public boolean existTable(QTable table) {
        Database master = dbRouter.getMaster();
        if (table.getSchemeName() == null || table.getSchemeName().isEmpty()) {
            table.setSchemeName(master.getSchemeName());
        }
        if (table.getSourceName() == null || table.getSourceName().isEmpty()) {
            table.setSourceName(master.getSourceName());
        }
        DatabaseSql databaseSql = master.getDclDialect().existTable(table);
        databaseSql.setDatabase(dbRouter.get(table.getSourceName()));
        int existTable = dcl.existTable(databaseSql);
        return existTable > 0;
    }

    public boolean existField(QField field) {
        Database master = dbRouter.getMaster();
        if (field.getSchemeName() == null || field.getSchemeName().isEmpty()) {
            field.setSchemeName(master.getSchemeName());
        }
        if (field.getSourceName() == null || field.getSourceName().isEmpty()) {
            field.setSourceName(master.getSourceName());
        }
        DatabaseSql databaseSql = master.getDclDialect().existField(field);
        databaseSql.setDatabase(dbRouter.get(field.getSourceName()));
        int existField = dcl.existField(databaseSql);
        return existField > 0;
    }
}
